﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace MovieDB.Common.Exceptions
{
    public static class ExceptionHelper
    {
        public static void HandleException(Exception ex)
        {
            var uniqueConstraintException = GetUniqueConstraintException(ex);
            if (uniqueConstraintException != null)
            {
                throw uniqueConstraintException;
            }

            throw ex;
        }

        private static UniqueConstraintViolationException GetUniqueConstraintException(Exception ex)
        {
            if (ex == null)
            {
                return null;
            }

            UniqueConstraintViolationException result = null;
            if (ex is SqlException)
            {
                if (IsUniqueConstraintViolation((SqlException)ex))
                {
                    result = new UniqueConstraintViolationException(ex);
                }
            }
            else
            {
                Exception innerException = ex.InnerException;
                result = GetUniqueConstraintException(innerException);
            }

            return result;
        }

        private static bool IsUniqueConstraintViolation(SqlException sqlException)
        {
            int number = sqlException.Number;
            int classNumber = sqlException.Class;

            // This is only valid for SQL Server
            return (number == 2601 && classNumber == 14);
        }
    }
}
